<template>
  <div>
    <form-drawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="行驶证" prop="drivingLicense">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            accept="image/jpg,image/png"
            :http-request="handleUploadImg"
          >
            <img v-if="form.drivingLicense" :src="form.drivingLicense" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="车牌号" prop="licensePlate">
          <el-autocomplete
            v-model="form.licensePlate"
            :fetch-suggestions="handleQuerySearchAsync"
            :trigger-on-focus="false"
            value-key="licensePlate"
            placeholder="请输入车牌号"
            clearable
            @select="handleSelectLicensePlate"
            style="width: 100%"
            ><template #default="{ item }">
              <span>{{ item.licensePlate }}</span>
              <span class="mx-4">{{ item.customerInfo.customerName }}</span>
              <span>{{ item.customerInfo.phone }}</span>
            </template></el-autocomplete
          >
        </el-form-item>
        <el-form-item label="车架号(vin)" prop="vin">
          <el-input v-model="form.vin" placeholder="请输入车架号" clearable />
        </el-form-item>
        <el-form-item label="车主姓名" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入车主姓名" clearable />
        </el-form-item>
        <el-form-item label="车主电话" prop="customerPhone"
          ><el-input v-model="form.customerPhone" placeholder="请输入车主电话" clearable
        /></el-form-item>
        <el-form-item label="车型" prop="vehicleModel">
          <el-input v-model="form.vehicleModel" placeholder="请输入车型" clearable />
        </el-form-item>
        <el-form-item label="接车公里数" prop="mileageNum">
          <el-input
            v-model="form.mileageNum"
            type="number"
            :min="1"
            placeholder="请输入车量当前里程数"
            clearable
            v-integer-number
          >
            <template #append>公里</template>
          </el-input>
        </el-form-item>
        <el-form-item label="保险到期日期" prop="insuranceExpireTime">
          <el-date-picker
            v-model="form.insuranceExpireTime"
            type="date"
            placeholder="选择保险到期日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="年检到期日期" prop="annualExpireTime">
          <el-date-picker
            v-model="form.annualExpireTime"
            type="date"
            placeholder="选择年检到期日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="燃料(能源类型)" prop="energyType">
          <el-select
            v-model="form.energyType"
            placeholder="请选择燃料(能源类型)"
            clearable
            filterable
          >
            <el-option
              v-for="item in energyTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="接车师傅" prop="pickCarUserId">
          <el-select v-model="form.pickCarUserId" placeholder="请选择接车师傅" clearable>
            <el-option
              v-for="item in useRepair.masterList"
              :key="(item as any).value"
              :label="(item as any).name"
              :value="(item as any).id"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </form-drawer>
  </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { useInitForm } from "@/hooks/useCommon";
import useRepairStore from "@/stores/modules/repair";
import FormDrawer from "@/components/FormDrawer.vue";
import { showLoading, hideLoading, compressImage } from "@/utils/index";
import { energyTypeList } from "@/enum/index";
import { getCarListApi } from "@/api/repair";
import { openRepairOrderApi, editRepairOrderApi } from "@/api/examine";
import { uploadFileApi, ocrIdentifyApi } from "@/api/user";

const emit = defineEmits(["success"]);
const useRepair = useRepairStore();
// 开维修单
const { formDrawerRef, drawerTitle, form, rules, formRef, handleCreate, handleEdit, handleSubmit } =
  useInitForm({
    form: {
      carId: "",
      customerId: "",
      id: "",
      drivingLicense: "",
      licensePlate: "",
      vin: "",
      customerName: "",
      customerPhone: "",
      vehicleModel: "",
      mileageNum: "",
      insuranceExpireTime: "",
      annualExpireTime: "",
      energyType: "",
      pickCarUserId: ""
    },
    rules: {
      drivingLicense: [{ required: true, message: "请上传行驶证", trigger: "change" }],
      licensePlate: [{ required: true, message: "请输入车牌号", trigger: "blur" }],
      vin: [
        { required: true, message: "请输入车架号", trigger: "blur" },
        { min: 17, max: 17, message: "车架号长度为17位", trigger: "blur" }
      ],
      customerName: [{ required: true, message: "请输入车主姓名", trigger: "blur" }],
      customerPhone: [
        { required: true, message: "请输入车主电话", trigger: "blur" },
        {
          validator: (rule: any, value: string, callback: any) => {
            if (!/^1[3-9]\d{9}$|^0\d{2,3}-\d{7,8}$/.test(value)) {
              callback(new Error("请输入正确的号码,座机用-"));
            } else {
              callback();
            }
          }
        }
      ],
      vehicleModel: [{ required: true, message: "请输入车辆型号", trigger: "blur" }],
      mileageNum: [{ required: true, message: "请输入行驶里程", trigger: "blur" }],
      annualExpireTime: [{ required: true, message: "请输入年检到期时间", trigger: "blur" }],
      energyType: [{ required: true, message: "请选择燃料(能源类型)", trigger: "blur" }]
    },
    createData: openRepairOrderApi,
    updateData: editRepairOrderApi,
    success: () => {
      emit("success");
    }
  });
// 图片上传
const handleUploadImg = async (params: any) => {
  const { file } = params;
  let result: any = file;
  if (result.size > 1024 * 1024) {
    // 压缩图片
    result = await compressImage(file, 0.5);
  }
  if (result.size / 1024 / 1024 > 1) {
    ElMessage.error("照片大小不能超过 1M");
    return false;
  }
  const formData = new FormData();
  formData.append("file", result);
  const res: any = await uploadFileApi(formData);
  if (res) {
    form.drivingLicense = res[0].accessUrl;
    hadleOCRIdentification(res[0].accessUrl);
  }
};
// ocr识别
const hadleOCRIdentification = async (imgUrl: string) => {
  try {
    showLoading();
    const res: any = await ocrIdentifyApi({ imgUrl });
    form.licensePlate = res.plate_num_b;
    form.vin = res.vin;
    form.customerName = res.owner;
    form.vehicleModel = res.model;
    res.plate_num_b && handleGetInfoByLicensePlate(res.plate_num_b);
  } finally {
    hideLoading();
  }
};

// 根据车牌搜索信息
const handleGetInfoByLicensePlate = async (licensePlate: string) => {
  const res: any = await getCarListApi({ licensePlate });
  if (res.length) {
    form.customerPhone = res[0].customerInfo.phone;
  }
};

// 车牌号搜索
const handleQuerySearchAsync = async (queryString: string, cb: any) => {
  const res = await getCarListApi({ licensePlate: queryString });
  cb(res);
};

// 选择车牌号
const handleSelectLicensePlate = (item: any) => {
  form.drivingLicense = item.drivingLicense;
  form.vin = item.vin;
  form.customerName = item.customerInfo.customerName;
  form.customerPhone = item.customerInfo.phone;
  form.vehicleModel = item.vehicleModel;
  form.energyType = item.energyType;
};

defineExpose({
  handleCreate,
  handleEdit
});
</script>
<style scoped lang="scss">
.avatar-uploader {
  border: 1px dashed var(--el-border-color);
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>
